package com.hzb.erp.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzb.erp.wechat.entity.WxMenuEntity;
import com.hzb.erp.wechat.mapper.WxMenuMapper;
import com.hzb.erp.wechat.pojo.wxMenu.WxMenuTypeEnum;
import com.hzb.erp.wechat.service.WxMenuService;
import com.hzb.erp.wechat.utils.WxMenuUtils;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p> 微信菜单配置表 服务实现类 </p>
 */
@Service
public class WxMenuServiceImpl extends ServiceImpl<WxMenuMapper, WxMenuEntity> implements WxMenuService {
    @Override
    public List<WxMenuEntity> menuList() {
        LambdaQueryWrapper<WxMenuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(WxMenuEntity::getId);
        List<WxMenuEntity> menuList = this.baseMapper.selectList(wrapper);
        return WxMenuUtils.buildMenuTree(menuList);
    }

    @Override
    public boolean menuSave(List<WxMenuEntity> wxMenus) {
        List<WxMenuEntity> flatMenu = WxMenuUtils.menuListFlat(wxMenus);
        List<WxMenuEntity> insertMenu = new LinkedList<>();
        for(WxMenuEntity menu: flatMenu) {
            this.validMenuData(menu);
            if(!"add".equals(menu.getType()) && !"default".equals(menu.getType())) {
                this.customMenu(menu);
                insertMenu.add(menu);
            }
        }
        if(CollectionUtils.isEmpty(insertMenu)) {
            throw new RuntimeException("没有有效菜单");
        }
        // 删除一遍
        LambdaQueryWrapper<WxMenuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(WxMenuEntity::getId, 0L);
        this.baseMapper.delete(wrapper);
        // 批量新增替换掉原来的
        return this.saveBatch(insertMenu);
    }

    @Override
    public WxMenu getProdMenu() {
        LambdaQueryWrapper<WxMenuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(WxMenuEntity::getId);
        List<WxMenuEntity> menuList = this.baseMapper.selectList(wrapper);
        if(CollectionUtils.isEmpty(menuList)) {
            throw new RuntimeException("请先设置菜单");
        }
        WxMenu menuProd = new WxMenu();

        for(WxMenuEntity menu: menuList) {
            if(menu.getPid() == 0) {
                WxMenuButton button = new WxMenuButton();
                this.parseCustomMenu(menu);
                button.setType(menu.getType());
                button.setName(menu.getName());
                button.setKey(menu.getKeyCode());
                button.setUrl(menu.getUrl());
                button.setMediaId(menu.getMediaId());
                button.setAppId(menu.getAppid());
                button.setPagePath(menu.getPagepath());
                button.setSubButtons(new ArrayList<>());

                for(WxMenuEntity subMenu: menuList) {
                    if(subMenu.getPid().equals(menu.getId())) {
                        WxMenuButton subBtn = new WxMenuButton();
                        subBtn.setType(subMenu.getType());
                        subBtn.setName(subMenu.getName());
                        subBtn.setKey(subMenu.getKeyCode());
                        subBtn.setUrl(subMenu.getUrl());
                        subBtn.setMediaId(subMenu.getMediaId());
                        subBtn.setAppId(subMenu.getAppid());
                        button.getSubButtons().add(subBtn);
                    }
                }
                if(button.getSubButtons().size() > 0) {
                    button.setType(null);
                }
                menuProd.getButtons().add(button);
            }
        }
        return menuProd;
    }

    /**
    * 自定义在菜单设置
    * */
    private void customMenu(WxMenuEntity wxMenu) {
        // 发送文字的key设置
        if(WxMenuTypeEnum.SEND_TEXT.getLabel().equals(wxMenu.getType())) {
            wxMenu.setKeyCode(WxMenuTypeEnum.SEND_TEXT.getLabel().toUpperCase() + "_" + wxMenu.getId());
        }
    }

    /**
     * 解析自定义菜单设置 主要是send_text
     * */
    private void parseCustomMenu(WxMenuEntity wxMenu) {
        // 发送文字的方式在微信官方没有，这里做了自定义
        if(WxMenuTypeEnum.SEND_TEXT.getLabel().equals(wxMenu.getType())) {
            wxMenu.setType(WxConsts.MenuButtonType.CLICK);
            wxMenu.setUrl(null);
        }
    }

    /**
    * 验证参数
    * */
    private void validMenuData(WxMenuEntity wxMenu) {

        if(StringUtils.isBlank(wxMenu.getName())) {
            throw new RuntimeException("有菜单名未设置");
        }
        if(StringUtils.isBlank(wxMenu.getType())) {
            throw new RuntimeException("有菜单类型未设置");
        }
        if(wxMenu.getPid() != null && wxMenu.getPid() != 0 && "normal".equals(wxMenu.getType())) {
            throw new RuntimeException("菜单[" + wxMenu.getName() + "]菜单内容设置无效");
        }
        if(WxMenuTypeEnum.VIEW.getLabel().equals(wxMenu.getType()) || WxMenuTypeEnum.MINIPROGRAM.getLabel().equals(wxMenu.getType())) {
            if(StringUtils.isBlank(wxMenu.getUrl())) {
                throw new RuntimeException("菜单[" + wxMenu.getName() + "]缺少参数url");
            }
        }

        if(WxMenuTypeEnum.MINIPROGRAM.getLabel().equals(wxMenu.getType())) {
            if(StringUtils.isBlank(wxMenu.getAppid())) {
                throw new RuntimeException("菜单[" + wxMenu.getName() + "]缺少参数appid");
            }
            if(StringUtils.isBlank(wxMenu.getPagepath())) {
                throw new RuntimeException("菜单[" + wxMenu.getName() + "]缺少参数pagepath");
            }
        }

        if(WxMenuTypeEnum.CLICK.getLabel().equals(wxMenu.getType())
                || WxMenuTypeEnum.SCANCODE_PUSH.getLabel().equals(wxMenu.getType())
                || WxMenuTypeEnum.SCANCODE_WAITMSG.getLabel().equals(wxMenu.getType())) {
            if(StringUtils.isBlank(wxMenu.getKeyCode())) {
                throw new RuntimeException("菜单[" + wxMenu.getName() + "]缺少参数key");
            }
        }

        if(WxMenuTypeEnum.MEDIA_ID.getLabel().equals(wxMenu.getType())) {
            if(StringUtils.isBlank(wxMenu.getMediaId())) {
                throw new RuntimeException("菜单[" + wxMenu.getName() + "]缺少参数media_id");
            }
        }

        if(WxMenuTypeEnum.ARTICLE_ID.getLabel().equals(wxMenu.getType()) || WxMenuTypeEnum.ARTICLE_VIEW_LIMITED.getLabel().equals(wxMenu.getType())) {
            if(StringUtils.isBlank(wxMenu.getArticleId())) {
                throw new RuntimeException("菜单[" + wxMenu.getName() + "]缺少参数article_id");
            }
        }
        if(WxMenuTypeEnum.SEND_TEXT.getLabel().equals(wxMenu.getType()) && StringUtils.isBlank(wxMenu.getSendText())) {
            throw new RuntimeException("菜单[" + wxMenu.getName() + "]缺少发送内容");
        }

    }

}
